﻿using Newtonsoft.Json;
using StackExchange.Redis;

namespace Zws.Redis
{
    public class RedisClient
    {
        private readonly ConnectionMultiplexer redisServer;
        private readonly IDatabase redisDb;

        public RedisClient(RedisConfig config)
        {
            redisServer = ConnectionMultiplexer.Connect($"{config.Ip}:{config.Port}", option =>
            {
                option.Password = config.Password;
            });
            redisDb = redisServer.GetDatabase(config.Db);
        }

        public async Task<bool> SetByKeyAsync(string key, string value)
        {
            return await redisDb.StringSetAsync(key, value);
        }
        public async Task<string?> GetByKeyAsync(string key)
        {
            return await redisDb.StringGetAsync(key);
        }

        public async Task<T?> GetByKeyAsync<T>(string key) where T : class
        {
            var val = await GetByKeyAsync(key);
            return val == null ? default(T) : JsonConvert.DeserializeObject<T>(val);
        }
    }
}
